//
//  QSUserManager.m
//  DigitalEconomy_iOS
//
//  Created by Ding on 2020/3/23.
//  Copyright © 2020 DingC. All rights reserved.
//

#import "QSUserManager.h"
// 文件路径
#define kFile [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0] stringByAppendingPathComponent:@"account.data"]
@implementation QSUserManager
single_implementation(QSUserManager)
- (id)init
{
    if (self = [super init]) {
        _user = [NSKeyedUnarchiver unarchiveObjectWithFile:kFile];
    }
    return self;
}

- (void)saveUser:(QSUserModel *)user
{
    _user = user;
    [NSKeyedArchiver archiveRootObject:user toFile:kFile];
}

- (void)removeUser
{
    _user = nil;
    if ([[NSFileManager defaultManager] fileExistsAtPath:kFile]) {
        [[NSFileManager defaultManager]removeItemAtPath:kFile error:nil];
    }
}

- (void)turnToHomeViewController {
    if ([[UIViewController currentViewController] isKindOfClass:NSClassFromString(@"QSMainTabBarController")]) {
        return;
    }
    
    [UIApplication sharedApplication].keyWindow.rootViewController = [[QSMainTabBarController alloc] init];
    
    if (self.LoginSuccessBlock) {
        self.LoginSuccessBlock();
    }
}

- (void)turnToLoginViewController {
    if ([[UIViewController currentViewController] isKindOfClass:NSClassFromString(@"QSLoginViewController")]) {
        return;
    }
    [self removeUser];
    [UIApplication sharedApplication].keyWindow.rootViewController = [[QSBaseNavigationController alloc] initWithRootViewController:[[QSLoginViewController alloc] init]];
    CATransition * transition = [[CATransition alloc] init];
    transition.type = @"fade";
    transition.duration = 0.2;
    [[UIApplication sharedApplication].keyWindow.layer addAnimation:transition forKey:nil];
    
    if (self.NeedLoginBlock) {
        self.NeedLoginBlock();
    }
}

@end
